<template>
	<div class="faceRegister">
		<div class="container">
			<video ref="video" width="500" height="500" autoplay></video>
			</di>
			<canvas style="display: none;" id="canvas" ref="canvas" width="500" height="500"></canvas>
			<div class="btns-div">
				<div class="fg-item">
					<el-button @click="goBack">返 回</el-button>
				</div>
				<div class="fg-item">
					<el-button type="primary" @click="takePhoto">注 册</el-button>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import FaceRegisterService from './FaceRegisterService.js';
	export default {
		name: "FaceLogin",
		data() {
			return {

			}
		},
		created() {
			this.getVideo();
		},
		beforeDestroy() {
			let video = this.$refs.video;
			video.srcObject.getTracks()[0].stop();
		},
		methods: {
			goBack() {
				this.$router.back();
			},
			getVideo() {
				this.$nextTick(() => {

					var video = this.$refs.video; //这个对应的是ref属性

					navigator.mediaDevices.getUserMedia({
							"video": true
						})
						.then(function(stream) {
							try {
								video.src = window.URL.createObjectURL(stream);
							} catch (e) {
								video.srcObject = stream;
							}

							video.onloadmetadate = function(e) {
								video.play();

							}
						});
				})

			},
			takePhoto() {
				this.$nextTick(() => {
					this.context = this.$refs.canvas.getContext("2d");
					this.context.drawImage(this.$refs.video, 0, 0, 330, 250);
					let photo = document.getElementById("canvas").toDataURL(
						"image/png");
					let pfile = this.dataURLtoFile(photo, 'photo')
					console.log(pfile);
					let formData = new FormData();
					formData.append('file', pfile);
					FaceRegisterService.faceRegisterService(formData, res => {
						console.log(res);
						if (res.message) {
							this.$message({
								message: '注册成功！',
								type: 'success',
								duration: 1500,
							});
							this.$router.back();
						}else{
							this.$message.error('注册失败！');
						}
						
					})
				})
			},
			getBase64() {
				var imgSrc = document.getElementById("canvas").toDataURL(
					"image/png");

				return imgSrc.split("base64,")[1];

			},
			dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(',')
				var mime = arr[0].match(/:(.*?);/)[1]
				var bstr = atob(arr[1])
				var n = bstr.length
				var u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new File([u8arr], filename, {
					type: mime
				})
			},
		}
	}
</script>

<style scoped lang="less">
	.faceRegister {
		width: 100%;
		height: 100vh;
		background-color: #404040;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.container {
		text-align: center;
	}

	.btns-div {
		display: flex;
		justify-content: space-around;
	}
	
	.fg-item{
		
	}
</style>
